/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "tinyxml.h"

#include "hhdIGameObjectTreeHolder.h"

#include "hhdGameObject.h"
#include "hhdTScene.h"
#include "hhdTPrefab.h"

#include "hhdContentLibrary.h"

#include "hhdMAddGameObject.h"
#include "hhdMRemoveGameObject.h"
#include "hhdMMoveGameObject.h"
#include "hhdMSetActivation.h"
#include "hhdMSetTransform.h"
#include "hhdMath.h"
#include "hhdMessenger.h"
#include "hhdRegistry.h"

namespace hhd
{
    HObjectCPP( hhd::GameObject )

    size_t GameObject::_count = 0;

    GameObject::GameObject()
        : _transform(this),
          _child_game_objects(16),
          _components(16),
          _name(""),
          _owner(NULL)
    {
        _parent_game_object = NULL;

        _layer = -1;
        _id = _count++;
        _active = true;
        registerMessageCallback<MAddGameObject>(GameObject::handle_add_game_object_message);
        registerMessageCallback<MRemoveGameObject>(GameObject::handle_remove_game_object_message);
        registerMessageCallback<MMoveGameObject>(GameObject::handle_move_game_object_message);
        registerMessageCallback<MSetActivation>(GameObject::handle_set_activation_message);
        registerMessageCallback<MSetTransform>(GameObject::handle_set_transform);
    }

    GameObject::~GameObject()
    {

    }

    void GameObject::handle_add_game_object_message(IMessageReceiver* receiver, IMessage* message)
    {
        GameObject* _this = (GameObject*)receiver;
        if(MAddGameObject* agom = message->as<MAddGameObject>())
        {

            GameObject* new_child = agom->_to_add;
            if(new_child == NULL)
            {
                error("You must add a GameObject to your AddGameObjectMessage");
            }
            if(_this == new_child)
            {
                error("Adding GameObject to itself is a bad idea");
            }
            //_this->addChildGameObject(new_child, _this);

            if(_this->getScene() == NULL)
            {
                error("Sending a message to a GameObject without a Scene is a bad idea");
            }

            new_child->setOwner(_this->getOwner());
            new_child->_layer = _this->_layer+1;

            new_child->setParentGameObject(_this);
            _this->_child_game_objects.add(new_child);

            if(agom->_initialize)
            {
                new_child->initialize();
            }
            // set dirty flag in scene so i twill rebuild the game object table

            _this->getScene()->setDirtyLayer(_this->_layer);
        }
    }

    void GameObject::handle_remove_game_object_message(IMessageReceiver* receiver, IMessage* message)
    {
        GameObject* _this = (GameObject*)receiver;
        if(MRemoveGameObject* rgom = message->as<MRemoveGameObject>())
        {
            GameObject* to_remove = rgom->_to_remove;
            if(to_remove == NULL)
            {
                error("You must add a GameObject to your RemoveGameObjectMessage");
            }

            if(to_remove->_parent_game_object == NULL)
            {
                error("Cannot remove root GameObject from scene");
            }

            // set dirty flag in scene so it will rebuild the game object table
            _this->getScene()->setDirtyLayer(_this->_layer);
            // remove!
            _this->_child_game_objects.swapRemove(to_remove);

            if(rgom->_release == true)
            {
                Factory::release(to_remove);
            }

        }
    }

    /** check to make sure we aren't adding a game object to it's own child **/
    void GameObject::handle_move_game_object_message(IMessageReceiver* receiver, IMessage* message)
    {
        GameObject* _this = (GameObject*)receiver;
        if(MMoveGameObject* mgom = message->as<MMoveGameObject>())
        {
            // set dirty flag in scene so it will rebuild the game object table
            _this->getScene()->setDirtyLayer(_this->_layer);

            // remove game object from it's parent
            _this->_child_game_objects.swapRemove(mgom->_to_move);
            // now send message to new parent to add the game object
            MAddGameObject* agom = Factory::acquire<MAddGameObject>();
            agom->setGameObject(mgom->_to_move, false);
            Messenger::sendMessage(agom, mgom->_new_parent);
        }
    }

    void GameObject::handle_set_activation_message(IMessageReceiver* receiver, IMessage* message)
    {
        GameObject* _this = (GameObject*)receiver;
        if(MSetActivation* sam = message->as<MSetActivation>())
        {
            set_activity(_this, sam->getActivity());
        }
    }

    void GameObject::set_activity(GameObject* in_go, bool in_activity)
    {
        if(in_go->_active != in_activity)
        {
            in_go->_active = in_activity;
            // set component activities
            for(size_t k = 0; k < in_go->componentCount(); k++)
            {
                in_go->getComponent(k)->setActivity(in_activity);
            }

            // recurse
            for(size_t k = 0; k < in_go->gameObjectCount(); k++)
            {
                set_activity(in_go->getChildGameObject(k), in_activity);
            }
        }
    }

    void GameObject::handle_set_transform(IMessageReceiver* me, IMessage* msg)
    {
        if(const MSetTransform* stf = msg->as<MSetTransform>())
        {
            GameObject* _this = (GameObject*)me;
            if(stf->_p_set)
            {
                _this->getTransform().setPosition(stf->_position);
            }
            if(stf->_o_set)
            {
                _this->getTransform().setRotation(stf->_orientation);
            }
        }
    }

    IGameObjectTreeHolder* GameObject::getOwner()
    {
        return _owner;
    }

    GameObject& GameObject::operator=(const GameObject& other)
    {
        this->copy( other );
        return *this;
    }

    // prepare game object for return to Factory
    void GameObject::reset()
    {
        for(size_t i = 0; i < _child_game_objects.size(); i++ )
        {
            Factory::release( _child_game_objects[i] );
        }
        for(size_t j = 0; j < _components.size(); j++)
        {
            Factory::release( _components[j] );
        }

        _parent_game_object = 0;
        _owner = NULL;

        _child_game_objects.clear();
        _components.clear();
    }

    GameObject* GameObject::getChildByName(const String& in_name)
    {
        for(size_t k = 0; k < _child_game_objects.size(); k++)
        {
            if(_child_game_objects[k]->_name == in_name)
            {
                return _child_game_objects[k];
            }
        }

        for(size_t k = 0; k < _child_game_objects.size(); k++)
        {
            GameObject* result = _child_game_objects[k]->getChildByName(in_name);
            if(result)
            {
                return result;
            }
        }
        return NULL;
    }

    void GameObject::update(const GameTimer& in_gt)
    {
        error("Deprecated");

        // update components
        size_t component_count = _components.size();
        for(size_t k = 0; k < component_count; k++)
        {
            _components[k]->update(in_gt);
        }

        // update child game objects
        size_t children = _child_game_objects.size();
        for(size_t k = 0; k < children; k++)
        {
            _child_game_objects[k]->update(in_gt);
        }
    }

    void GameObject::shallowUpdate(const GameTimer& in_gt)
    {
        if(_active)
        {
            // update components
            size_t component_count = _components.size();
            for(size_t k = 0; k < component_count; k++)
            {
                _components[k]->update(in_gt);
            }
        }
    }

    // get this game objects transform
    Transform& GameObject::getTransform()
    {
        return _transform;
    }
    
    int GameObject::id() const
    {
        return _id;
    }

    // get game objects globalname
    const String& GameObject::name() const
    {
        return _name;
    }

    /** Scene methods **/

    TScene* GameObject::getScene()
    {
        TScene* result;
        _owner ? result = _owner->as<TScene>() : result = NULL;
        return result;
    }

    /** Game Object methods **/

    GameObject* GameObject::getChildGameObject(size_t in_index)
    {
        if(in_index >= _child_game_objects.size())
        {
            return NULL;
        }

        return _child_game_objects[in_index];
    }

    void GameObject::addChildGameObject(GameObject* in_game_object)
    {
        if(getScene() && getScene()->getScenePhase() == GameObjectUpdate)
        {
            error("The GameTree cannot be modified directly during GameObject update due to potential multithreading issues;  To add new GameObjects, use an AddGameObjectMessage");
        }

        if(in_game_object->getParentGameObject() == this)
        {
            error("This object is already a child of this parent.");
        }

        in_game_object->_owner = _owner;
        in_game_object->_layer = _layer+1;

        in_game_object->setParentGameObject(this);
        _child_game_objects.add(in_game_object);
    }

    void GameObject::removeChildGameObject(GameObject* in_game_object)
    {
        if(getScene() && getScene()->getScenePhase() == GameObjectUpdate)
        {
            error("The GameTree cannot be modified directly during GameObject update due to potential multithreading issues;  To remove old GameObjects, use a RemoveGameObjectMessage");
        }

        _child_game_objects.swapRemove(in_game_object);
    }

    size_t GameObject::gameObjectCount() const
    {
        return _child_game_objects.size();
    }

    size_t GameObject::gameObjectSubtreeCount() const
    {
        size_t count = 1;//this one
        for( size_t i = 0; i < _child_game_objects.size(); i++ )
        {
            count += _child_game_objects[i]->gameObjectSubtreeCount();
        }
        return count;
    }

    GameObject* GameObject::getParentGameObject()
    {
        return _parent_game_object;
    }

    void GameObject::setParentGameObject(GameObject* in_game_object)
    {
        _parent_game_object = in_game_object;
    }

    /** Component Methods **/

    void GameObject::addComponent(IComponent* in_component)
    {
        in_component->_parent = this;
        _components.add(in_component);
    }

    IComponent* GameObject::getComponent(size_t in_index)
    {
        if(in_index >= _components.size())
        {
            return NULL;
        }

        return _components[in_index];
    }

    size_t GameObject::componentCount() const
    {
        return _components.size();
    }

    /** Parsing methods **/

    void GameObject::initialize()
    {
        for(size_t k = 0; k < _components.size(); k++)
        {
            _components[k]->initialize();
        }

        for(size_t j = 0; j < _child_game_objects.size(); j++)
        {
            _child_game_objects[j]->initialize();
        }

        _transform.initialize(this);
    }

    void GameObject::setOwner(IGameObjectTreeHolder* in_owner)
    {
        _owner = in_owner;
        for( size_t i = 0; i < _child_game_objects.size(); i++ )
        {
            _child_game_objects[i]->setOwner( in_owner );
        }
    }

    GameObject* GameObject::readXML(const String& in_xml, IGameObjectTreeHolder* in_owner)
    {
        setOwner(in_owner);

        TiXmlDocument document;
        document.Parse(in_xml);

        TiXmlElement* node = document.RootElement();

        if(node)
        {
            float posX = 0.0f;
            float posY = 0.0f;
            float posZ = 0.0f;

            float orientX = 0.0f;
            float orientY = 0.0f;
            float orientZ = 0.0f;

            float scaleX = 1.0f;
            float scaleY = 1.0f;
            float scaleZ = 1.0f;

            //check to see if it uses a Prefab to fill itself in.
            String prefab_path(node->Attribute("prefabPath"));
            if( prefab_path.length() != 0 )
            {
                String prefab_key;
                //load the prefab, if its already loaded its handled internally
                _owner->loadPrefab(prefab_path);

                //get the prefab now that its loaded
                _owner->getPrefab(prefab_key, this);
            }

            //get a global name from file, or if not given, generate one.
            const char* name = node->Attribute("name");
            if(name == NULL)
            {
                StringBuilder sb;
                sb << "GameObject" << this->id();
                sb >> _name;
            }
            else
            {
                this->_name = name;
            }
            Vector3 position;
            Vector3 scale;

            //get the transform data, otherwise it is defaulted already
            node->QueryVector3Attribute("position", &position);
            _transform.setPosition(position);

            node->QueryVector3Attribute("scale", &scale);
            _transform.setScale(scale);

            Vector3 orientation;
            node->QueryVector3Attribute("orientation", &orientation);

            _transform.rotate(Math::Pi / 180.0f * orientation.x, Math::Pi / 180.0f * orientation.y, Math::Pi / 180.0f * orientation.z);

            //_transform->invalidateWorld();


            // this method is used to add game objects to the dictionary so we can get gameobjects by name
            if(_owner && _owner->is<TScene>())
            {
                _owner->as<TScene>()->addGameObject(this);
            }

            //go for child components and child game objects
            TiXmlNode* child = 0;
            while( (child = node->IterateChildren(child)) )
            {
                TiXmlElement* child_element = child->ToElement();
                if(!child_element) // probably a comment but more importantly not parseable as an element
                {
                    continue;
                }

                String tag(child_element->Value());

                if(tag.equals("GameObject"))
                {
                    String go_xml(*child_element);

                    GameObject* go = Factory::acquire<GameObject>();
                    this->addChildGameObject(go);
                    go->readXML(go_xml, in_owner);
                }
                else if(tag.equals("Component"))
                {
                    const char* component_type = child_element->Attribute("type");
                    if(component_type != NULL)
                    {
                        // get the prototype from the index so we can parse
                        IComponent* prototype = Registry<IComponent>::createFromRegistry(component_type);

                        if(prototype == NULL)
                        {
                            StringBuilder sb;
                            sb << "Couldn't find Prototype for component \"" << component_type << "\"" << endl;
                            sb << "Have you registered it in the ComponentIndex?" << endl;
							String string;
							sb >> string;
                            error(string);
                        }

                        // now get a new instance of the prototype from the factory
                        IComponent* new_component = (IComponent*)Factory::acquire(prototype);

                        // dump xml to string
                        String co_xml(*child_element);

                        // parse it!
                        this->addComponent(new_component);
                        new_component->readXML(co_xml);

                    }

                }

            }
        }
        return this;

    }

    GameObject& GameObject::copy(const GameObject& in_other)
    {
        //get transform
        _transform.copy(in_other._transform, this);
        _name = in_other._name;
        //_owner = in_other._owner;

        //release old components
        for(size_t i = 0; i < _components.size(); i++)
        {
            Factory::release( this->_components[i] );
        }

        _components.clear();

        //release old game objects
        for(size_t i = 0; i < _child_game_objects.size(); i++)
        {
            Factory::release( this->_child_game_objects[i] );
        }

        _child_game_objects.clear();

        //get child components
        for(size_t k = 0; k < in_other._components.size(); k++)
        {
            this->addComponent(in_other._components[k]->clone());
        }

        //get child game objects
        for(size_t k = 0; k < in_other._child_game_objects.size(); k++)
        {
            this->addChildGameObject(in_other._child_game_objects[k]->clone());
        }

        //return
        return *this;
    }

    GameObject* GameObject::clone() const
    {
        GameObject* result = Factory::acquire<GameObject>();

        result->copy( *this );

        return result;
    }

    PrintStream& operator<< (PrintStream& in_stream, const GameObject& go)
    {

        go.print_game_object(in_stream, 0);
        return in_stream;
    }

    void GameObject::print_game_object(PrintStream& in_stream, size_t tree_depth) const
    {
        for(size_t k = 0; k < tree_depth; k++)
        {
            in_stream << ' ';
        }
        in_stream << name() << " - " << endl;
        for(size_t k = 0; k < tree_depth; k++)
        {
            in_stream << ' ';
        }
        in_stream << " global position: " << _transform.getWorldPosition() << endl;
        for(size_t k = 0; k < tree_depth; k++)
        {
            in_stream << ' ';
        }
        in_stream << " local position:  " << _transform.getLocalPosition() << endl;
        for(size_t k = 0; k < tree_depth; k++)
        {
            in_stream << ' ';
        }
        in_stream << " local rotation:  " << _transform.getLocalRotationEuler() << endl;

        for(size_t k = 0; k < this->componentCount(); k++)
        {
            for(size_t i = 0; i <= tree_depth; i++)
            {
                in_stream << ' ';
            }
            in_stream << "  " << _components[k]->componentName() << endl;
        }
        for(size_t k = 0; k < this->gameObjectCount(); k++)
        {
            _child_game_objects[k]->print_game_object(in_stream, tree_depth+1);
        }
    }
}
